package com.audaque.springboot.foshanupload.security.valid.rsp.validfail;

/**
 * @author zgb
 * @desc ...
 * @date 2022-08-10 00:44:26
 */

import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 鉴证失败处理器
 */
@Slf4j
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        exception.printStackTrace();
        log.error("鉴证失败处理器:"+exception.getMessage());

        String url = request.getRequestURL().toString();
        log.debug("url："+url);



        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();



        R r = new R<>();
        r.setSuccess(false);
        r.setCode(ResultCodeEnum.NOT_LOGIN.getCode());
        r.setMsg(ResultCodeEnum.NOT_LOGIN.getMsg());

        try {
            out.write(objectMapper.writeValueAsString(r));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }


    }
}
